import { TYPE } from './Tab';

//抽象类
abstract class Base {
  private _el: HTMLElement;
  private _tabItems: HTMLCollection;
  private _curIdx: number = 0;
  private _methodArr: any[] = [];
  //inner -> HTMLElement | pageItems -> HTMLCollection
  private _pageElement: HTMLElement | HTMLCollection;

  constructor(el: HTMLElement, type: TYPE) {
    this._el = el;
    this._tabItems = this._el.getElementsByClassName('tab-item');

    switch (type) {
      case TYPE.FADE:
        this._pageElement = this._el.getElementsByClassName('page-item');
        break;
      case TYPE.SLIDE:
        this._pageElement = this._el.getElementsByClassName(
          'inner'
        )[0] as HTMLElement;
      default:
        break;
    }

    this._init();
  }

  private _init() {
    this._bindEvent();
  }

  private _bindEvent() {
    this._el.addEventListener('click', this._setTab.bind(this), false);
  }

  //点击tab-item更改样式
  private _setTab(e: MouseEvent) {
    const tar = e.target as HTMLElement;
    const className = tar.className;

    //事件代理 点击某一项进行切换
    if (className === 'tab-item') {
      //还原样式
      this._tabItems[this._curIdx].className = 'tab-item';

      //找到当前项索引
      this._curIdx = [].indexOf.call(this._tabItems, tar);

      //更改样式
      this._tabItems[this._curIdx].className += ' active';

      //执行发布通知
      this.notify();
    }
  }

  //收集方法(订阅)
  protected getMethod(method: any) {
    this._methodArr.push(method);
  }

  //发布通知
  protected notify() {
    this._methodArr.forEach((item: any) => {
      item(this._pageElement, this._curIdx);
    });
  }
}

export default Base;
